import time

from django.utils.deprecation import MiddlewareMixin
from Home.tools.AuthQuery import g
from Home.tools.Myredis import r
from  django.http import JsonResponse

class MyMiddleware(MiddlewareMixin):


    def process_request(self, request):
        #设置白名单路径
        path_list=["/home/nav/loginView/","/home/nav/messageView/","/home/nav/","/"]
        print(request.path )
        #排除白名单路径
        if(request.path not in path_list):
            #获取token，并校验
            token = request.headers.get("token")

            #存在token
            if token:
                # 进行校验
                try:
                    data = g.jwt_decode(token)

                except:
                    return JsonResponse({"message": "token已经被修改", "code": 401})



                #看用户是否已经跳出
                if(r.getex_str(token)):
                    return JsonResponse({"message": "用户已经退出，不能访问", "code": 401})


                #看token是否已经过期
                exp=int(data['exp'])
                now=int(time.time())
                if(now > exp):
                    return JsonResponse({"message": "token已经过期，不能访问", "code": 401})



            else:
                return JsonResponse({"message":"token不存在","code":401})
        #获取token并校验




    def process_response(self, request, response):

        return response
